var app = getApp();
var url = app.url
Page({
  data: {
    showLoading: true, // 等待动画
    fzList: [],
    keepSheetHidden: true,
    keepSheetItems: [
      { bindtap: 'Menu1', txt: '全开' },
      { bindtap: 'Menu2', txt: '全关' },
      { bindtap: 'Menu3', txt: '取消' },
    ],
    menu: '',
    chidx: 0,// 选中地区下标
    opType: '',// 1==开，0==关
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    var name = wx.getStorageSync('userName')
    if (name == '' || name == null) {
      wx.showModal({
        title: '提示',
        content: "用户未登录",
        confirmText: '去登录',
        showCancel: false,
        success: function () {
          wx.redirectTo({
            url: '../login/login',
          })
        }
      })
    } else {
      this.getUserMeters()
    }
  },
  onShow: function () {
    // 页面显示
  },
  onReady: function () {
    // 页面渲染完成
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  onPullDownRefresh: function () {
    this.setData({ fzList: [], keepSheetHidden: true, showLoading: true })
    this.getUserMeters()
  },
  checkLogin: function () {
    var name = wx.getStorageSync('userName')
    if (name == '' || name == null) {
      wx.showModal({
        title: '提示',
        content: "用户未登录",
        confirmText: '去登录',
        showCancel: false,
        success: function () {
          wx.navigateTo({
            url: '../login/login',
          })
        }
      })
    }
  },
  actionSheetTap: function (e) {
    var idx = e.currentTarget.dataset.idx
    this.setData({
      chidx: idx, keepSheetHidden: !this.data.keepSheetHidden
    })
  },
  keepSheetChange: function () {
    this.setData({
      keepSheetHidden: !this.data.keepSheetHidden
    })
  },
  bindMenu1: function () {
    this.setData({
      menu: 1, opType: 1, 
      keepSheetHidden: !this.data.keepSheetHidden
    })
    this.lightSubmit()
  },
  bindMenu2: function () {
    this.setData({
      menu: 2, opType: 0, 
      keepSheetHidden: !this.data.keepSheetHidden
    })
    this.lightSubmit()
  },
  bindMenu3: function () {
    this.setData({
      menu: 3, opType: '',
      keepSheetHidden: !this.data.keepSheetHidden
    })
  },
  getUserMeters: function () {
    var that = this
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var params = { userName: wx.getStorageSync('userName') }
    var encodingStr = app.ecbEncrypto(params)
    wx.request({
      url: url + '/xywl/appUserMeters.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        if (rest.res == 0) {
         that.optionList(rest.gasMeterList)
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
      },
      complete: function () {
        wx.stopPullDownRefresh()
        that.setData({ showLoading: false })
      }
    })
  },
  // 操作数据分组
  optionList: function (list) {
    var arr = {}
    if(list.length > 0){
      for(var i = 0; i < list.length; i++){
        var st = list[i][0].SWITCH_STATUS
        var result = ['--', '--', '--', '--'];
        if (st != '' && st != undefined){
          // var str1 = st.replace(new RegExp('1', 'gm'), '连接')
          // var str2 = str1.replace(new RegExp('0', 'gm'), '断开')
          var sp= st.split('|');
          for(var j=0;j<sp.length;j++){
            result[j] = sp[j];
          }
        }
        list[i][0].SWITCH_STATUS = result;
        if (arr[list[i][0].DEPTNAME]){
          arr[list[i][0].DEPTNAME].push(list[i][0])
        }else{
          var lr = new Array()
          lr.push(list[i][0])
          arr[list[i][0].DEPTNAME] = lr
        }
      }
    }
    var objs = []
    for (i in arr) {
      var ob = { name: i, array: arr[i]}
      objs.push(ob)
    }
    this.setData({ fzList: objs })
  },
  // 跳转
  showZdByName: function (e) {
    var idx = e.currentTarget.dataset.idx
    var list = this.data.fzList
    wx.setStorageSync("area" + idx, list[idx])// 缓存数据
    wx.navigateTo({
      url: '../control/area?idx='+idx,
    })
  },
  // 控制路灯事件
  lightSubmit: function () {
    var that = this
    var idx = that.data.chidx
    var list = that.data.fzList
    var array = list[idx].array
    var nos = ''
    var msg = ""
    wx.showLoading({
      title: '提交中',
    })
    for(var i = 0;i < array.length; i++){
      if (array[i].IS_ONLINE == 1){
        nos = array[i].TERMINAL_ADDRESS
        var flag = true
        var header = { 'content-type': 'application/x-www-form-urlencoded' }
        var params = {
          userName: wx.getStorageSync('userName'), meterAddr: nos, operationId: that.data.opType, branch: 1
        }
        var encodingStr = app.ecbEncrypto(params)
        wx.request({
          url: url + '/xywl/pullSwitchMeter.htm',
          data: encodingStr,
          method: 'POST',
          header: header,
          success: function (res) {
            var decodingStr = app.ecbDecrypto(res.data)
            var rest = JSON.parse(decodingStr)
            if (rest.res == 0) {
              var respone = rest.respone
              if (respone.strBackFlag == 1) {
               
              } else {
                msg = "设置失败，请重试！"
                flag = false
              }

            } else {
              that.data.msg = rest.errorMsg
              flag = false
            }
          }
        })
        if (!flag) {
          break
        }
      }
    }
    wx.hideLoading()
    if (!flag) {
      wx.showModal({
        title: '提示',
        content: that.data.msg,
        showCancel: false
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '设置成功！',
        showCancel: false
      })
    }
  },

});